package com.sibu.yx.promotion.web.util;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.imageio.ImageIO;

import lombok.extern.slf4j.Slf4j;

/**
 * 图片压缩工具
* @ClassName: CompressUtil 
* @Description:
* @author yuwenbo
* @date 2016年8月8日 上午9:57:10 
*
 */
@Slf4j
public class ImageCompressUtil {
	    
	
	    @SuppressWarnings("restriction")
		public static void compressImage(OutputStream out, byte[] bytes, int dwidth, int dheight,String formate){
	    	BufferedImage image = new BufferedImage(dwidth, dheight,BufferedImage.TYPE_INT_RGB ); 
	    	BufferedInputStream stream = new BufferedInputStream(new ByteArrayInputStream(bytes), bytes.length);
			try {
				Image img = ImageIO.read(stream);
				int width =img.getWidth(null);
				int height =img.getHeight(null);
				if (width / height > dwidth / dheight) {  
					dheight= height * dwidth / width;  
			     } else {  
			    	 dwidth = width * dheight / height;  
			     } 
				image.getGraphics().drawImage(img, 0, 0, dwidth,dheight, null);
				ImageIO.write(image,formate, out);
				stream.close();
			} catch (IOException e) {
				log.error("[{}]", e);
			}
		}
}
